<template>
  <div class="outbound-edit-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>新增出库单</h2>
          <div>
            <el-button @click="goBack">返回</el-button>
            <el-button type="primary" @click="handleSubmit">保存</el-button>
          </div>
        </div>
      </template>

      <!-- 基础信息 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <h3>基础信息</h3>
        </template>
        
        <el-form :model="outboundForm" :rules="rules" ref="formRef" label-width="120px">
          <el-row :gutter="20">
            <!-- 出库单号 -->
            <el-col :span="12">
              <el-form-item label="出库单号" prop="outboundCode">
                <el-input v-model="outboundForm.outboundCode" placeholder="自动获取系统编号" disabled></el-input>
              </el-form-item>
            </el-col>
            
            <!-- 出库类型 -->
            <el-col :span="12">
              <el-form-item label="出库类型" prop="inOutTypeId">
                <el-select 
                  v-model="outboundForm.inOutTypeId" 
                  placeholder="请选择出库类型" 
                  @change="handleOutTypeChange"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in outTypeOptions"
                    :key="item.inOutTypeId"
                    :label="item.inOutTypeName"
                    :value="item.inOutTypeId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <!-- 仓库名称 -->
            <el-col :span="12">
              <el-form-item label="仓库名称" prop="warehouseId">
                <el-select 
                  v-model="outboundForm.warehouseId" 
                  placeholder="请选择仓库"
                  @change="handleWarehouseChange"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in warehouseOptions"
                    :key="item.id"
                    :label="item.warehouseName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            
            <!-- 出库日期 -->
            <el-col :span="12">
              <el-form-item label="出库日期" prop="outboundDate">
                <el-date-picker
                  v-model="outboundForm.outboundDate"
                  type="date"
                  placeholder="请选择出库日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <!-- 关联单号 -->
            <el-col :span="12">
              <el-form-item label="关联单号" prop="relatedOrderId">
                <div style="display: flex; gap: 10px;">
                  <el-input 
                    v-model="outboundForm.relatedOrderCode" 
                    placeholder="请点击选择关联单号"
                    readonly
                    style="flex: 1"
                  >
                    <template #append>
                      <el-button 
                        @click="openOrderSelectDialog" 
                        :disabled="!outboundForm.inOutTypeId"
                        icon="Search"
                      >
                        选择
                      </el-button>
                    </template>
                  </el-input>
                  <el-checkbox v-model="isRelatedSalesOrder" disabled>关联销售单号</el-checkbox>
                </div>
              </el-form-item>
            </el-col>
            
            <!-- 客户名称 -->
            <el-col :span="12">
              <el-form-item label="客户名称">
                <el-input v-model="outboundForm.customerName" placeholder="请输入客户名称" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <!-- 收货人 -->
            <el-col :span="12">
              <el-form-item label="收货人">
                <el-input v-model="outboundForm.consignee" placeholder="请输入收货人"></el-input>
              </el-form-item>
            </el-col>
            
            <!-- 联系方式 -->
            <el-col :span="12">
              <el-form-item label="联系方式">
                <el-input v-model="outboundForm.contactPhone" placeholder="请输入联系方式"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <!-- 经办人 -->
            <el-col :span="12">
              <el-form-item label="经办人" prop="userId">
                <el-select 
                  v-model="outboundForm.userId" 
                  placeholder="请选择经办人"
                  @change="handleUserChange"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in userOptions"
                    :key="item.user_Id || item.user_id"
                    :label="item.userTrueName"
                    :value="item.user_Id || item.user_id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 备注 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input
                  v-model="outboundForm.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注信息"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 出库明细 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <h3>出库明细</h3>
            <div>
              <el-button type="primary" size="small" @click="addOutboundDetail">添加</el-button>
              <el-button type="danger" size="small" @click="removeOutboundDetail">移除</el-button>
            </div>
          </div>
        </template>

        <!-- 出库明细表格 -->
        <el-table :data="outboundDetails" border stripe style="width: 100%">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" width="60"></el-table-column>
          <el-table-column prop="goodsCode" label="货品编号" width="120"></el-table-column>
          <el-table-column prop="goodsName" label="货品名称" width="150"></el-table-column>
          <el-table-column prop="specModel" label="规格型号" width="120"></el-table-column>
          <el-table-column label="单价" width="100">
            <template #default="scope">
              {{ Number(scope.row.salesPrice || 0).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="退货数量" width="100">
            <template #default="scope">
              {{ scope.row.salesQuantity || 0 }}
            </template>
          </el-table-column>
          <el-table-column label="金额" width="120">
            <template #default="scope">
              {{ Number(scope.row.salesAmount || 0).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="currentInventory" label="已出库" width="80">
            <template #default="scope">
              {{ scope.row.salesQuantity - scope.row.remainingQuantity }}
            </template>
          </el-table-column>
          <el-table-column prop="remainingQuantity" label="未出库" width="80">
            <template #default="scope">
              <span :style="{ color: scope.row.remainingQuantity > 0 ? '#E6A23C' : '#67C23A' }">
                {{ scope.row.remainingQuantity || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="本次出库数量" width="140">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.outboundQuantity" 
                :min="0" 
                :max="scope.row.remainingQuantity"
                :precision="0"
                size="small"
                style="width: 100%"
                @change="handleOutboundQuantityChange(scope.row)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="出库库位" width="120">
            <template #default="scope">
              <el-select v-model="scope.row.storageLocationId" placeholder="请选择库位" size="small">
                <el-option label="默认库位" value="1"></el-option>
              </el-select>
            </template>
          </el-table-column>1161+1749+
          <el-table-column label="批次号" width="100">
            <template #default="scope">
              <el-input 
                v-model="scope.row.batchNumber" 
                size="small"
                placeholder="批次号"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="生产日期" width="120">
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.productionDate"
                type="date"
                placeholder="yyyy/mm/dd"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                size="small"
                style="width: 100%"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="120">
            <template #default="scope">
              <el-input 
                v-model="scope.row.remark" 
                size="small"
                placeholder="备注"
                style="width: 100%"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" @click="removeDetailRow(scope.$index)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 底部操作按钮 -->
      <div style="margin-top: 20px; text-align: center; padding: 20px;">
        <el-button size="large" @click="goBack">取消</el-button>
        <el-button type="primary" size="large" @click="handleSubmit" style="margin-left: 20px;">
          提交出库单
        </el-button>
      </div>
    </el-card>

    <!-- 选择销售订单弹窗 -->
    <el-dialog 
      v-model="salesOrderDialogVisible" 
      title="选择销售单" 
      width="80%" 
      :close-on-click-modal="false"
    >
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="salesOrderSearchForm" class="search-form">
        <el-form-item label="销售单号">
          <el-input v-model="salesOrderSearchForm.shopOrderCode" placeholder="请输入销售单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select v-model="salesOrderSearchForm.status" placeholder="请选择单据状态" clearable>
            <el-option label="未出库" value="0"></el-option>
            <el-option label="部分出库" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户">
          <el-select v-model="salesOrderSearchForm.customerId" placeholder="请选择客户" clearable>
            <el-option label="客户一" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售负责人">
          <el-input v-model="salesOrderSearchForm.salesPerson" placeholder="请输入销售负责人" clearable></el-input>
        </el-form-item>
        <el-form-item label="销售部门">
          <el-input v-model="salesOrderSearchForm.department" placeholder="请输入销售部门" clearable></el-input>
        </el-form-item>
        <el-form-item label="销售日期">
          <el-select v-model="salesOrderSearchForm.dateRange" placeholder="请选择销售日期" clearable>
            <el-option label="今天" value="today"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSalesOrderSearch">重置</el-button>
          <el-button type="primary" @click="searchSalesOrders">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 销售订单表格 -->
      <el-table 
        :data="salesOrderList" 
        border 
        stripe 
        style="width: 100%" 
        v-loading="salesOrderLoading"
        @selection-change="handleSalesOrderSelectionChange"
      >
        <el-table-column type="radio" width="50">
          <template #default="scope">
            <el-radio 
              v-model="selectedSalesOrder" 
              :label="scope.row.id"
              @change="handleSalesOrderSelect(scope.row)"
            >&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="shopOrderCode" label="销售单号" width="150"></el-table-column>
        <el-table-column prop="status" label="单据状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'danger' : 'warning'">
              {{ scope.row.status === 0 ? '未出库' : '部分出库' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="shopOrderDate" label="销售日期" width="120"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="120"></el-table-column>
        <el-table-column prop="deptName" label="销售部门" width="120"></el-table-column>
        <el-table-column prop="userName" label="销售负责人" width="120"></el-table-column>
        <el-table-column prop="shopAllNum" label="货品数量" width="100"></el-table-column>
        <el-table-column prop="shopAllMoney" label="销售金额" width="120"></el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: center;">
        <el-pagination
          v-model:current-page="salesOrderCurrentPage"
          v-model:page-size="salesOrderPageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="salesOrderTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSalesOrderSizeChange"
          @current-change="handleSalesOrderCurrentChange"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="salesOrderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSalesOrderSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择退货订单弹窗 -->
    <el-dialog 
      v-model="returnOrderDialogVisible" 
      title="选择退货单" 
      width="80%" 
      :close-on-click-modal="false"
    >
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="returnOrderSearchForm" class="search-form">
        <el-form-item label="退货单号">
          <el-input v-model="returnOrderSearchForm.returnOrderCode" placeholder="请输入退货单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="returnOrderSearchForm.supplierName" placeholder="请输入供应商" clearable></el-input>
        </el-form-item>
        <el-form-item label="退货日期">
          <el-date-picker
            v-model="returnOrderSearchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetReturnOrderSearch">重置</el-button>
          <el-button type="primary" @click="searchReturnOrders">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 退货订单表格 -->
      <el-table 
        :data="returnOrderList" 
        border 
        stripe 
        style="width: 100%" 
        v-loading="returnOrderLoading"
      >
        <el-table-column type="radio" width="50">
          <template #default="scope">
            <el-radio 
              v-model="selectedReturnOrder" 
              :label="scope.row.id"
              @change="handleReturnOrderSelect(scope.row)"
            >&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="returnOrderCode" label="退货单号" width="150"></el-table-column>
        <el-table-column prop="returnOrderDate" label="退货日期" width="120"></el-table-column>
        <el-table-column prop="purchaseOrderCode" label="进货单号" width="120"></el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="120"></el-table-column>
        <el-table-column prop="contact" label="联系人" width="100"></el-table-column>
        <el-table-column prop="contactPhone" label="联系方式" width="120"></el-table-column>
        <el-table-column prop="deptName" label="部门" width="120"></el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: center;">
        <el-pagination
          v-model:current-page="returnOrderCurrentPage"
          v-model:page-size="returnOrderPageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="returnOrderTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleReturnOrderSizeChange"
          @current-change="handleReturnOrderCurrentChange"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="returnOrderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmReturnOrderSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 明细选择弹窗 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="选择出库明细" 
      width="90%" 
      :close-on-click-modal="false"
    >
      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form" style="margin-bottom: 20px;">
        <el-form-item>
          <el-input placeholder="请输入货品编号/名称" clearable style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="请选择单位" clearable style="width: 120px;">
            <el-option label="瓶" value="瓶"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button>重置</el-button>
          <el-button type="primary">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 明细选择表格 -->
      <el-table 
        :data="availableDetails" 
        border 
        stripe 
        style="width: 100%" 
        @selection-change="handleDetailSelectionChange"
        max-height="400"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="goodsCode" label="货品编号" width="120"></el-table-column>
        <el-table-column prop="goodsName" label="货品名称" width="150"></el-table-column>
        <el-table-column prop="specModel" label="规格型号" width="120"></el-table-column>
        <el-table-column label="单价" width="100">
          <template #default="scope">
            {{ Number(scope.row.salesPrice || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="100">
          <template #default="scope">
            {{ scope.row.salesQuantity || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120">
          <template #default="scope">
            {{ Number(scope.row.salesAmount || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <!-- 进货价格列（仅退货订单显示） -->
        <el-table-column v-if="availableDetails.some(item => item.orderType === 'return')" prop="purchasePrice" label="进货价格" width="100">
          <template #default="scope">
            {{ Number(scope.row.purchasePrice || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="outboundedQuantity" label="已出库" width="80">
          <template #default="scope">
            <span style="color: #909399;">{{ scope.row.outboundedQuantity || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remainingQuantity" label="未出库" width="80">
          <template #default="scope">
            <span :style="{ 
              color: scope.row.remainingQuantity > 0 ? '#E6A23C' : '#67C23A',
              fontWeight: 'bold'
            }">
              {{ scope.row.remainingQuantity || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.remainingQuantity > 0 ? 'warning' : 'success'" 
              size="small"
            >
              {{ scope.row.remainingQuantity > 0 ? '待出库' : '已出库' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 统计信息 -->
      <div style="margin-top: 15px; padding: 10px; background-color: #f5f7fa; border-radius: 4px;">
        <el-row :gutter="20">
          <el-col :span="6">
            <span style="color: #606266;">总明细数：</span>
            <span style="font-weight: bold; color: #409EFF;">{{ availableDetails.length }}</span>
          </el-col>
          <el-col :span="6">
            <span style="color: #606266;">已选择：</span>
            <span style="font-weight: bold; color: #67C23A;">{{ selectedDetailIds.length }}</span>
          </el-col>
          <el-col :span="6">
            <span style="color: #606266;">待出库：</span>
            <span style="font-weight: bold; color: #E6A23C;">
              {{ availableDetails.filter(item => item.remainingQuantity > 0).length }}
            </span>
          </el-col>
          <el-col :span="6">
            <span style="color: #606266;">已出库：</span>
            <span style="font-weight: bold; color: #67C23A;">
              {{ availableDetails.filter(item => item.remainingQuantity === 0).length }}
            </span>
          </el-col>
        </el-row>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddDetails">
            确定添加 ({{ selectedDetailIds.length }})
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from 'axios';

// 路由
const router = useRouter();

// 表单引用
const formRef = ref();

// 出库单表单数据
const outboundForm = reactive({
  outboundCode: '', // 出库单号
  inOutTypeId: null, // 出库类型ID
  inOutTypeName: '', // 出库类型名称
  warehouseId: null, // 仓库ID
  warehouseName: '', // 仓库名称
  outboundDate: '', // 出库日期
  relatedOrderId: null, // 关联单号ID
  relatedOrderCode: '', // 关联单号编码
  customerName: '', // 客户名称
  consignee: '', // 收货人
  contactPhone: '', // 联系方式
  userId: null, // 经办人ID
  userName: '', // 经办人姓名
  remark: '' // 备注
});

// 出库明细数据
const outboundDetails = ref([]);

// 下拉选项数据
const outTypeOptions = ref([]); // 出库类型选项
const warehouseOptions = ref([]); // 仓库选项
const userOptions = ref([]); // 用户选项
const relatedOrderOptions = ref([]); // 关联单号选项

// 是否关联销售单号
const isRelatedSalesOrder = ref(false);

// 可选明细数据（从订单加载的所有明细）
const availableDetails = ref([]); // 可选的明细列表
const detailDialogVisible = ref(false); // 明细选择弹窗
const selectedDetailIds = ref([]); // 选中的明细ID列表

// 弹窗控制
const salesOrderDialogVisible = ref(false); // 销售订单弹窗
const returnOrderDialogVisible = ref(false); // 退货订单弹窗

// 销售订单相关数据
const salesOrderList = ref([]); // 销售订单列表
const salesOrderLoading = ref(false); // 销售订单加载状态
const salesOrderCurrentPage = ref(1); // 销售订单当前页
const salesOrderPageSize = ref(20); // 销售订单每页大小
const salesOrderTotal = ref(0); // 销售订单总数
const selectedSalesOrder = ref(null); // 选中的销售订单ID
const selectedSalesOrderData = ref(null); // 选中的销售订单数据

// 销售订单搜索表单
const salesOrderSearchForm = reactive({
  shopOrderCode: '', // 销售单号
  status: '', // 单据状态
  customerId: '', // 客户
  salesPerson: '', // 销售负责人
  department: '', // 销售部门
  dateRange: '' // 销售日期
});

// 退货订单相关数据
const returnOrderList = ref([]); // 退货订单列表
const returnOrderLoading = ref(false); // 退货订单加载状态
const returnOrderCurrentPage = ref(1); // 退货订单当前页
const returnOrderPageSize = ref(20); // 退货订单每页大小
const returnOrderTotal = ref(0); // 退货订单总数
const selectedReturnOrder = ref(null); // 选中的退货订单ID
const selectedReturnOrderData = ref(null); // 选中的退货订单数据

// 退货订单搜索表单
const returnOrderSearchForm = reactive({
  returnOrderCode: '', // 退货单号
  supplierName: '', // 供应商
  dateRange: [] // 退货日期范围
});

// 表单验证规则
const rules = {
  inOutTypeId: [{ required: true, message: '请选择出库类型', trigger: 'change' }],
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  outboundDate: [{ required: true, message: '请选择出库日期', trigger: 'change' }],
  userId: [{ required: true, message: '请选择经办人', trigger: 'change' }]
};

// 初始化页面数据
onMounted(() => {
  generateOutboundCode();
  loadOutTypes();
  loadWarehouses();
  loadUsers();
});

// 生成出库单号
const generateOutboundCode = () => {
  const now = new Date();
  const timestamp = now.getTime();
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  outboundForm.outboundCode = `CK${timestamp}${random}`;
};

// 加载出库类型数据
const loadOutTypes = async () => {
  try {
    const response = await axios.get('/api/Outbound/GetInOutTypes/GetInOutTypes');
    
    console.log('出库类型API返回数据:', response.data);
    
    if (response.data && response.data.code === 200) {
      outTypeOptions.value = response.data.data || [];
      console.log('出库类型选项:', outTypeOptions.value);
    } else {
      ElMessage.error('获取出库类型失败');
    }
  } catch (error) {
    console.error('加载出库类型失败:', error);
    ElMessage.error('加载出库类型失败');
  }
};

// 加载仓库数据
const loadWarehouses = async () => {
  try {
    console.log('开始加载仓库数据...');
    const response = await axios.get('/api/Outbound/GetWarehouses/GetWarehouses');
    
    console.log('仓库API返回数据:', response.data);
    
    if (response.data && response.data.code === 200) {
      warehouseOptions.value = response.data.data || [];
      console.log('仓库选项:', warehouseOptions.value);
    } else {
      ElMessage.error('获取仓库列表失败');
    }
  } catch (error) {
    console.error('加载仓库数据失败:', error);
    ElMessage.error('加载仓库数据失败');
  }
};

// 加载用户数据（经办人）
const loadUsers = async () => {
  try {
    console.log('开始加载用户数据...');
    const response = await axios.get('/api/Outbound/GetUsers/GetUsers');
    
    console.log('用户API返回数据:', response.data);
    
    if (response.data && response.data.code === 200) {
      userOptions.value = response.data.data || [];
      console.log('用户选项数量:', userOptions.value.length);
      console.log('用户选项详细数据:', userOptions.value);
      
      // 检查数据结构
      if (userOptions.value.length > 0) {
        console.log('第一个用户数据结构:', userOptions.value[0]);
        console.log('用户ID字段:', userOptions.value[0].user_Id || userOptions.value[0].user_id);
        console.log('用户姓名字段:', userOptions.value[0].userTrueName);
      }
    } else {
      console.error('用户API返回错误:', response.data);
      ElMessage.error('获取用户列表失败');
    }
  } catch (error) {
    console.error('加载用户数据失败:', error);
    if (error.response) {
      console.error('响应错误:', error.response.status, error.response.data);
    }
    ElMessage.error('加载用户数据失败');
  }
};

// 出库类型改变事件
const handleOutTypeChange = (value) => {
  console.log('选择的出库类型ID:', value);
  
  // 找到选中的出库类型
  const selectedType = outTypeOptions.value.find(item => item.inOutTypeId === value);
  if (selectedType) {
    outboundForm.inOutTypeName = selectedType.inOutTypeName;
    console.log('选择的出库类型名称:', selectedType.inOutTypeName);
    
    // 根据出库类型ID判断是否关联销售单号
    isRelatedSalesOrder.value = value === 16; // ID为16时关联销售单号
    
    // 清空之前的关联单号信息
    outboundForm.relatedOrderId = null;
    outboundForm.relatedOrderCode = '';
    outboundForm.customerName = '';
    outboundForm.consignee = '';
    outboundForm.contactPhone = '';
  }
};

// 仓库改变事件
const handleWarehouseChange = (value) => {
  console.log('选择的仓库ID:', value);
  
  // 找到选中的仓库
  const selectedWarehouse = warehouseOptions.value.find(item => item.id === value);
  if (selectedWarehouse) {
    outboundForm.warehouseName = selectedWarehouse.warehouseName;
    console.log('选择的仓库名称:', selectedWarehouse.warehouseName);
  }
};

// 经办人改变事件
const handleUserChange = (value) => {
  console.log('选择的用户ID:', value);
  
  // 找到选中的用户 - 兼容不同的字段名格式
  const selectedUser = userOptions.value.find(item => 
    (item.user_Id === value) || (item.user_id === value)
  );
  if (selectedUser) {
    outboundForm.userName = selectedUser.userTrueName;
    console.log('选择的用户姓名:', selectedUser.userTrueName);
  }
};


// 出库数量变化处理
const handleOutboundQuantityChange = (row) => {
  console.log('出库数量变化:', row.outboundQuantity, '最大可出库:', row.remainingQuantity);
  
  // 验证出库数量不能超过未出库数量
  if (row.outboundQuantity > row.remainingQuantity) {
    ElMessage.warning(`出库数量不能超过未出库数量 ${row.remainingQuantity}`);
    row.outboundQuantity = row.remainingQuantity;
  }
  
  // 验证出库数量不能小于0
  if (row.outboundQuantity < 0) {
    row.outboundQuantity = 0;
  }
};

// 添加出库明细
const addOutboundDetail = () => {
  if (!outboundForm.relatedOrderId) {
    ElMessage.warning('请先选择关联单号');
    return;
  }
  
  if (availableDetails.value.length === 0) {
    ElMessage.warning('没有可选的明细数据，请重新选择关联单号');
    return;
  }
  
  // 打开明细选择弹窗
  detailDialogVisible.value = true;
  selectedDetailIds.value = []; // 清空之前的选择
};

// 移除选中的出库明细
const removeOutboundDetail = () => {
  // 这里可以实现批量移除选中行的功能
  ElMessage.info('移除功能待实现');
};

// 移除单行明细
const removeDetailRow = (index) => {
  outboundDetails.value.splice(index, 1);
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate();
    
    // 验证是否有出库明细
    if (outboundDetails.value.length === 0) {
      ElMessage.warning('请添加出库明细');
      return;
    }
    
    // 验证出库明细是否填写了出库数量
    const invalidDetails = outboundDetails.value.filter(item => !item.outboundQuantity || item.outboundQuantity <= 0);
    if (invalidDetails.length > 0) {
      ElMessage.warning('请填写所有明细的出库数量');
      return;
    }
    
    // 确认提交对话框
    const outTypeText = outboundForm.inOutTypeId === 16 ? '销售订单出库' : '退货出库';
    const confirmResult = await ElMessageBox.confirm(
      `确认提交${outTypeText}单吗？\n出库单号：${outboundForm.outboundCode}\n明细数量：${outboundDetails.value.length}条`,
      '确认提交',
      {
        confirmButtonText: '确认提交',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).catch(() => false);
    
    if (!confirmResult) {
      return;
    }
    
    // 根据出库类型选择不同的提交接口
    if (outboundForm.inOutTypeId === 16) {
      // 销售订单出库
      await submitSalesOutbound();
    } else if (outboundForm.inOutTypeId === 14) {
      // 退货出库
      await submitReturnOutbound();
    } else {
      ElMessage.error('不支持的出库类型');
    }
  } catch (error) {
    console.error('表单验证失败:', error);
    ElMessage.error('请检查表单填写是否完整');
  }
};

// 销售订单出库提交
const submitSalesOutbound = async () => {
  try {
    console.log('开始提交销售订单出库...');
    
    // 构建销售订单出库数据结构（根据接口文档的字段）
    const salesOutboundData = {
      outboundCode: outboundForm.outboundCode,                    // 出库单号
      outInTypeId: Number(outboundForm.inOutTypeId),              // 出库类型ID (16)
      warehouseId: Number(outboundForm.warehouseId),              // 仓库ID
      outboundDate: outboundForm.outboundDate,                    // 出库日期 "2025-10-29T03:44:34.709Z"
      relationalID: Number(outboundForm.relatedOrderId),          // 关联销售订单ID
      contact: outboundForm.consignee || '',                      // 联系人
      consignee: outboundForm.consignee || '',                    // 收货人
      contactPhone: outboundForm.contactPhone || '',              // 联系方式
      userId: Number(outboundForm.userId),                        // 经办人ID
      remark: outboundForm.remark || '',                          // 备注
      
      // 汇总信息
      outboundAllNum: outboundDetails.value.reduce((sum, item) => sum + (Number(item.outboundQuantity) || 0), 0),
      outboundAllMoney: outboundDetails.value.reduce((sum, item) => sum + (Number(item.outboundQuantity) * Number(item.salesPrice) || 0), 0),
      outboundAllGoods: outboundDetails.value.map(item => `${item.goodsName}(${item.outboundQuantity}个)`).join('、'),
      
      // 销售订单出库明细
      details: outboundDetails.value.map(item => ({
        detailId: Number(item.relatedDetailId),                   // 销售订单明细ID
        storageId: Number(item.storageLocationId) || 1,           // 库位ID（默认值1）
        oneOutboundNum: Number(item.outboundQuantity),            // 本次出库数量
        batchNumber: item.batchNumber || '',                      // 批次号
        productionDate: item.productionDate || '',                // 生产日期
        remark: item.remark || ''                                 // 明细备注
      }))
    };
    
    console.log('销售订单出库提交数据:', salesOutboundData);
    
    // 调用销售订单出库接口
    const response = await axios.post('/api/Outbound/CreateSalesOutbound/CreateSalesOutbound', salesOutboundData);
    
    console.log('销售订单出库API返回:', response.data);
    
    if (response.data && response.data.code === 200) {
      ElMessage.success('销售订单出库单创建成功！');
      setTimeout(() => {
        router.push('/OutboundView');
      }, 1500);
    } else {
      ElMessage.error(response.data?.message || '销售订单出库单创建失败');
    }
  } catch (error) {
    console.error('销售订单出库提交失败:', error);
    if (error.response) {
      console.error('响应错误:', error.response.status, error.response.data);
      ElMessage.error(`销售订单出库提交失败: ${error.response.data?.message || error.response.statusText}`);
    } else {
      ElMessage.error('网络错误，请检查网络连接');
    }
  }
};

// 退货出库提交
const submitReturnOutbound = async () => {
  try {
    console.log('开始提交退货出库...');
    
    // 构建退货出库数据结构（根据接口文档的字段）
    const returnOutboundData = {
      outboundCode: outboundForm.outboundCode,                    // 出库单号
      outInTypeId: Number(outboundForm.inOutTypeId),              // 出库类型ID (14)
      warehouseId: Number(outboundForm.warehouseId),              // 仓库ID
      outboundDate: outboundForm.outboundDate,                    // 出库日期 "2025-10-29T03:44:10.825Z"
      relationalID: Number(outboundForm.relatedOrderId),          // 关联退货订单ID
      contact: outboundForm.consignee || '',                      // 联系人
      consignee: outboundForm.consignee || '',                    // 收货人
      contactPhone: outboundForm.contactPhone || '',              // 联系方式
      userId: Number(outboundForm.userId),                        // 经办人ID
      remark: outboundForm.remark || '',                          // 备注
      
      // 汇总信息
      outboundAllNum: outboundDetails.value.reduce((sum, item) => sum + (Number(item.outboundQuantity) || 0), 0),
      outboundAllMoney: outboundDetails.value.reduce((sum, item) => sum + (Number(item.outboundQuantity) * Number(item.salesPrice) || 0), 0),
      outboundAllGoods: outboundDetails.value.map(item => `${item.goodsName}(${item.outboundQuantity}个)`).join('、'),
      
      // 退货出库明细
      details: outboundDetails.value.map(item => ({
        detailId: Number(item.relatedDetailId),                   // 退货订单明细ID
        storageId: Number(item.storageLocationId) || 1,           // 库位ID（默认值1）
        oneOutboundNum: Number(item.outboundQuantity),            // 本次出库数量
        batchNumber: item.batchNumber || '',                      // 批次号
        productionDate: item.productionDate || '',                // 生产日期
        remark: item.remark || ''                                 // 明细备注
      }))
    };
    
    console.log('退货出库提交数据:', returnOutboundData);
    
    // 调用退货出库接口
    const response = await axios.post('/api/Outbound/CreateReturnOutbound/CreateReturnOutbound', returnOutboundData);
    
    console.log('退货出库API返回:', response.data);
    
    if (response.data && response.data.code === 200) {
      ElMessage.success('退货出库单创建成功！');
      setTimeout(() => {
        router.push('/OutboundView');
      }, 1500);
    } else {
      ElMessage.error(response.data?.message || '退货出库单创建失败');
    }
  } catch (error) {
    console.error('退货出库提交失败:', error);
    if (error.response) {
      console.error('响应错误:', error.response.status, error.response.data);
      ElMessage.error(`退货出库提交失败: ${error.response.data?.message || error.response.statusText}`);
    } else {
      ElMessage.error('网络错误，请检查网络连接');
    }
  }
};

// 返回列表页
const goBack = () => {
  router.push('/OutboundView');
};

// 打开订单选择弹窗
const openOrderSelectDialog = () => {
  if (!outboundForm.inOutTypeId) {
    ElMessage.warning('请先选择出库类型');
    return;
  }

  // 根据出库类型ID决定打开哪个弹窗
  if (outboundForm.inOutTypeId === 16) {
    // 销售订单出库
    salesOrderDialogVisible.value = true;
    loadSalesOrders();
  } else if (outboundForm.inOutTypeId === 14) {
    // 进货退货出库
    returnOrderDialogVisible.value = true;
    loadReturnOrders();
  } else {
    ElMessage.warning('当前出库类型暂不支持选择关联单号');
  }
};

// 加载销售订单数据
const loadSalesOrders = async () => {
  try {
    salesOrderLoading.value = true;
    console.log('开始加载销售订单数据...');
    
    const params = {
      pageIndex: salesOrderCurrentPage.value,
      pageSize: salesOrderPageSize.value
    };
    
    // 添加搜索条件
    if (salesOrderSearchForm.shopOrderCode) {
      params.shopOrderCode = salesOrderSearchForm.shopOrderCode;
    }
    if (salesOrderSearchForm.status !== '') {
      params.status = salesOrderSearchForm.status;
    }
    if (salesOrderSearchForm.customerId) {
      params.customerId = salesOrderSearchForm.customerId;
    }
    
    const response = await axios.get('/api/Outbound/GetSalesOrders/GetSalesOrders/16', { params });
    console.log('销售订单API返回数据:', response.data);
    
    if (response.data && response.data.code === 200) {
      const data = response.data.data?.data || [];
      salesOrderList.value = data;
      salesOrderTotal.value = response.data.data?.totalCount || response.data.data?.total || data.length || 0;
      console.log('销售订单列表:', salesOrderList.value);
    } else {
      ElMessage.error('获取销售订单失败');
    }
  } catch (error) {
    console.error('加载销售订单失败:', error);
    ElMessage.error('加载销售订单失败');
  } finally {
    salesOrderLoading.value = false;
  }
};

// 加载退货订单数据
const loadReturnOrders = async () => {
  try {
    returnOrderLoading.value = true;
    console.log('开始加载退货订单数据...');
    
    const params = {
      pageIndex: returnOrderCurrentPage.value,
      pageSize: returnOrderPageSize.value
    };
    
    // 添加搜索条件
    if (returnOrderSearchForm.returnOrderCode) {
      params.returnOrderCode = returnOrderSearchForm.returnOrderCode;
    }
    if (returnOrderSearchForm.supplierName) {
      params.supplierName = returnOrderSearchForm.supplierName;
    }
    if (returnOrderSearchForm.dateRange && returnOrderSearchForm.dateRange.length === 2) {
      params.startDate = returnOrderSearchForm.dateRange[0];
      params.endDate = returnOrderSearchForm.dateRange[1];
    }
    
    const response = await axios.get('/api/Outbound/GetReturnOrders/GetReturnOrders/14', { params });
    console.log('退货订单API返回数据:', response.data);
    
    if (response.data && response.data.code === 200) {
      const data = response.data.data?.data || [];
      returnOrderList.value = data;
      returnOrderTotal.value = response.data.data?.totalCount || response.data.data?.total || data.length || 0;
      console.log('退货订单列表:', returnOrderList.value);
    } else {
      ElMessage.error('获取退货订单失败');
    }
  } catch (error) {
    console.error('加载退货订单失败:', error);
    ElMessage.error('加载退货订单失败');
  } finally {
    returnOrderLoading.value = false;
  }
};

// 销售订单选择事件
const handleSalesOrderSelect = (row) => {
  selectedSalesOrderData.value = row;
  console.log('选中的销售订单:', row);
};

// 退货订单选择事件
const handleReturnOrderSelect = (row) => {
  selectedReturnOrderData.value = row;
  console.log('选中的退货订单:', row);
};

// 确认销售订单选择
const confirmSalesOrderSelection = async () => {
  if (!selectedSalesOrderData.value) {
    ElMessage.warning('请选择一个销售订单');
    return;
  }
  
  const selectedOrder = selectedSalesOrderData.value;
  
  // 填充关联单号信息
  outboundForm.relatedOrderId = selectedOrder.id;
  outboundForm.relatedOrderCode = selectedOrder.shopOrderCode;
  outboundForm.customerName = selectedOrder.customerName;
  outboundForm.consignee = selectedOrder.contact;
  outboundForm.contactPhone = selectedOrder.contactPhone;
  
  console.log('已选择销售订单:', {
    id: selectedOrder.id,
    code: selectedOrder.shopOrderCode,
    customerName: selectedOrder.customerName
  });
  
  salesOrderDialogVisible.value = false;
  ElMessage.success('已选择销售订单: ' + selectedOrder.shopOrderCode);
  
  // 加载销售订单明细到可选列表（不直接添加到出库明细表格）
  await loadAvailableDetails(selectedOrder.id, 'sales');
};

// 确认退货订单选择
const confirmReturnOrderSelection = async () => {
  if (!selectedReturnOrderData.value) {
    ElMessage.warning('请选择一个退货订单');
    return;
  }
  
  const selectedOrder = selectedReturnOrderData.value;
  
  // 填充关联单号信息
  outboundForm.relatedOrderId = selectedOrder.id;
  outboundForm.relatedOrderCode = selectedOrder.returnOrderCode;
  outboundForm.customerName = selectedOrder.supplierName; // 退货单使用供应商名称
  outboundForm.consignee = selectedOrder.contact;
  outboundForm.contactPhone = selectedOrder.contactPhone;
  
  console.log('已选择退货订单:', {
    id: selectedOrder.id,
    code: selectedOrder.returnOrderCode,
    supplierName: selectedOrder.supplierName
  });
  
  returnOrderDialogVisible.value = false;
  ElMessage.success('已选择退货订单: ' + selectedOrder.returnOrderCode);
  
  // 加载退货订单明细到可选列表（不直接添加到出库明细表格）
  await loadAvailableDetails(selectedOrder.id, 'return');
};

// 销售订单搜索
const searchSalesOrders = () => {
  salesOrderCurrentPage.value = 1;
  loadSalesOrders();
};

// 重置销售订单搜索
const resetSalesOrderSearch = () => {
  Object.keys(salesOrderSearchForm).forEach(key => {
    salesOrderSearchForm[key] = '';
  });
  searchSalesOrders();
};

// 退货订单搜索
const searchReturnOrders = () => {
  returnOrderCurrentPage.value = 1;
  loadReturnOrders();
};

// 重置退货订单搜索
const resetReturnOrderSearch = () => {
  returnOrderSearchForm.returnOrderCode = '';
  returnOrderSearchForm.supplierName = '';
  returnOrderSearchForm.dateRange = [];
  searchReturnOrders();
};

// 销售订单分页事件
const handleSalesOrderSizeChange = (size) => {
  salesOrderPageSize.value = size;
  loadSalesOrders();
};

const handleSalesOrderCurrentChange = (page) => {
  salesOrderCurrentPage.value = page;
  loadSalesOrders();
};

// 退货订单分页事件
const handleReturnOrderSizeChange = (size) => {
  returnOrderPageSize.value = size;
  loadReturnOrders();
};

const handleReturnOrderCurrentChange = (page) => {
  returnOrderCurrentPage.value = page;
  loadReturnOrders();
};

// 销售订单选择变化事件（多选，这里暂时不用）
const handleSalesOrderSelectionChange = (selection) => {
  // 这里可以处理多选逻辑，当前使用单选
};

// 统一的加载可选明细方法
const loadAvailableDetails = async (orderId, orderType) => {
  try {
    let apiUrl = '';
    let detailsData = [];
    
    if (orderType === 'sales') {
      // 销售订单明细
      apiUrl = `/api/Outbound/GetSalesOrderDetails/GetSalesOrderDetails/${orderId}`;
      console.log('开始加载销售订单明细，订单ID:', orderId);
    } else if (orderType === 'return') {
      // 退货订单明细
      apiUrl = `/api/Outbound/GetReturnOrderDetails/GetReturnOrderDetails/${orderId}`;
      console.log('开始加载退货订单明细，订单ID:', orderId);
    }
    
    const response = await axios.get(apiUrl);
    console.log('订单明细API返回数据:', response.data);
    
    if (response.data && response.data.code === 200) {
      const details = response.data.data || [];
      console.log('明细数据详情:', details);
      
      // 输出第一条明细的所有字段，便于调试
      if (details.length > 0) {
        console.log('第一条明细的所有字段:', details[0]);
        console.log('字段列表:', Object.keys(details[0]));
      }
      
      if (orderType === 'sales') {
        // 销售订单明细处理 - 根据接口返回的真实字段
        detailsData = details.map(item => ({
          // 关联信息
          id: item.id,
          relatedDetailId: item.id,
          shopOrderId: item.shopOrderId,
          goodsId: item.goodsId,
          orderType: 'sales',
          
          // 货品信息（使用接口返回的真实字段）
          goodsName: item.goodsName || '',
          goodsCode: item.goodsCode || '',
          specModel: item.specModel || '',
          
          // 库存和出库信息（使用接口返回的真实字段）
          currentInventory: item.currentInventory || 0,
          salesPrice: item.shopOrderMoney && item.shopOrderNum ? 
                     (Number(item.shopOrderMoney) / Number(item.shopOrderNum)) : 0,
          salesQuantity: Number(item.shopOrderNum) || 0,
          salesAmount: Number(item.shopOrderMoney) || 0,
          shopOrderAllMoney: Number(item.shopOrderAllMoney) || 0, // 订单总金额
          
          // 出库状态计算
          outboundedQuantity: 0, // 已出库数量（暂时设为0，实际应从其他接口获取）
          remainingQuantity: Number(item.shopOrderNum) || 0, // 未出库数量（暂时等于销售数量）
          
          // 其他字段
          status: item.status,
          productTypeId: item.productTypeId,
          supplierId: item.supplierId,
          
          // 出库明细字段（初始值）
          outboundQuantity: 0,
          storageLocationId: '1', // 默认库位ID为1
          batchNumber: '',
          productionDate: '',
          remark: item.remark || ''
        }));
      } else if (orderType === 'return') {
        // 退货订单明细处理 - 根据接口返回的真实字段
        detailsData = details.map(item => ({
          // 关联信息
          id: item.id,
          relatedDetailId: item.id,
          returnOrderId: item.returnOrderId,
          purchaseOrderItemId: item.purchaseOrderItemId,
          goodsId: item.goodsId,
          orderType: 'return',
          
          // 货品信息（使用接口返回的真实字段）
          goodsName: item.goodsName || '',
          goodsCode: item.goodsCode || '',
          specModel: item.specModel || '',
          
          // 库存和退货信息（使用接口返回的真实字段）
          currentInventory: item.currentInventory || 0,
          salesPrice: item.returnMoney && item.returnNumber ? 
                     (Number(item.returnMoney) / Number(item.returnNumber)) : 0,
          salesQuantity: Number(item.returnNumber) || 0, // 退货数量
          salesAmount: Number(item.returnMoney) || 0, // 退货金额
          purchasePrice: Number(item.purchasePrice) || 0, // 进货价格
          
          // 出库状态计算
          outboundedQuantity: 0, // 已出库数量（暂时设为0，实际应从其他接口获取）
          remainingQuantity: Number(item.returnNumber) || 0, // 未出库数量（暂时等于退货数量）
          
          // 其他字段
          status: item.status,
          productTypeId: item.productTypeId,
          supplierId: item.supplierId,
          
          // 出库明细字段（初始值）
          outboundQuantity: 0,
          storageLocationId: '1', // 默认库位ID为1
          batchNumber: '',
          productionDate: '',
          remark: item.remarks || ''
        }));
      }
      
      availableDetails.value = detailsData;
      console.log('可选明细数据:', availableDetails.value);
      ElMessage.success(`已加载 ${details.length} 条可选明细，请点击"添加"按钮选择需要出库的明细`);
    } else {
      console.error('订单明细API返回错误:', response.data);
      ElMessage.error('获取订单明细失败');
      availableDetails.value = [];
    }
  } catch (error) {
    console.error('加载订单明细失败:', error);
    if (error.response) {
      console.error('响应错误:', error.response.status, error.response.data);
    }
    ElMessage.error('加载订单明细失败');
    availableDetails.value = [];
  }
};

// 明细选择相关方法
const handleDetailSelectionChange = (selection) => {
  selectedDetailIds.value = selection.map(item => item.id);
  console.log('选中的明细ID:', selectedDetailIds.value);
};

// 确认添加选中的明细
const confirmAddDetails = () => {
  if (selectedDetailIds.value.length === 0) {
    ElMessage.warning('请选择要添加的明细');
    return;
  }
  
  // 获取选中的明细数据
  const selectedDetails = availableDetails.value.filter(item => 
    selectedDetailIds.value.includes(item.id)
  );
  
  // 检查是否有重复的明细（避免重复添加）
  const existingDetailIds = outboundDetails.value.map(item => item.relatedDetailId);
  const newDetails = selectedDetails.filter(item => 
    !existingDetailIds.includes(item.relatedDetailId)
  );
  
  if (newDetails.length === 0) {
    ElMessage.warning('选中的明细已经存在于出库明细中');
    return;
  }
  
  // 添加新明细到出库明细表格
  outboundDetails.value.push(...newDetails);
  
  console.log('添加的新明细:', newDetails);
  console.log('当前出库明细:', outboundDetails.value);
  
  detailDialogVisible.value = false;
  ElMessage.success(`已添加 ${newDetails.length} 条明细到出库明细表格`);
};
</script>

<style scoped>
.outbound-edit-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-card {
  margin-bottom: 20px;
}

.section-card:last-child {
  margin-bottom: 0;
}
</style>
